import pygame
from pygame.sprite import Sprite


class Ship(Sprite):
    def __init__(self, settings, screen):
        """初始化飞船"""
        super(Ship, self).__init__()
        self.screen = screen
        self.settings = settings
        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()
        # 默认飞船位于屏幕中间位置
        self.rect.centerx = self.screen_rect.centerx
        self.rect.centery = self.screen_rect.centery
        # 默认飞船位于屏幕最底端
        self.rect.bottom = self.screen_rect.bottom

        # 移动标志,按键按下的时候为True,弹起的时候为False
        self.move_right = False
        self.move_left = False
        self.move_up = False
        self.move_down = False

        self.centerx = float(self.rect.centerx)
        self.centery = float(self.rect.centery)

    def blitme(self):
        """飞船位置设置"""
        self.screen.blit(self.image, self.rect)

    def update(self):
        """飞船左右移动"""
        if self.move_right and self.rect.right < self.screen_rect.right:
            self.centerx += self.settings.ship_speed_factor
        if self.move_left and self.rect.left > 0:
            self.centerx -= self.settings.ship_speed_factor
        if self.move_up and self.rect.top > 0:
            self.centery -= self.settings.ship_speed_factor
        if self.move_down and self.rect.bottom < self.screen_rect.bottom:
            self.centery += self.settings.ship_speed_factor
        self.rect.centerx = self.centerx
        self.rect.centery = self.centery

    def center_ship(self):
        self.centerx = self.screen_rect.centerx
        self.centery = self.screen_rect.bottom - self.image.get_rect().centery
